<?php

namespace ODP\FileWriter;
use ODP\Log;
use ODP\Util;

include "config.php";
include "Log.php";
include "Util.php";

class FileWriter
{
    private $threshold_time;
    function __construct()
    {

        $this->threshold_time = THRESHOLD_TIME;
        if($this->threshold_time<=0)
        {
            Log\Log::write('时间间隔配置错误');
            exit(0);
        }
    }

    function write($data=null)
    {
        Log\Log::write('收到的数据：'.$data);
        if($data)
        {

            $dest_filename = './data/tmp_trans/content_'.floor(time()/$this->threshold_time);
            file_put_contents($dest_filename, $data. "\r\n", FILE_APPEND);
            @chmod($dest_filename, 0666);

//            $dest_filename = $dest_filepath.'/content_'. Util\Util::get_millisecond().'_'.rand();
//            file_put_contents($dest_filename, $data, FILE_APPEND);
//            $this->trans_send($dest_filename); //暂定上报
        }
    }

    function trans_send($current_filename)
    {
        $url = '';
//        $url = 'http://www.epplink.net/cliprobe_curl/testtrans.php';

        $dest_file_path = './data/tmp_trans';
        $dest_filename_arr = array();
        Util\Util::read_file_dir($dest_file_path, $dest_filename_arr);

        if(!empty($dest_filename_arr))
        {
            foreach ($dest_filename_arr as $dest_filename)
            {
                if($dest_filename == $current_filename) continue;

                $file_content = file_get_contents($dest_filename);
                $file_content_arr = preg_split('/[\n(\r\n)]+/', $file_content);
                if(!empty($file_content_arr))
                {
                    $all_content = json_decode($file_content_arr[0], true);
                    $wifitalist = array();
                    foreach ($file_content_arr as $line_row)
                    {
                        if($line_row)
                        {
                            $line_row_arr = json_decode($line_row, true);
                            array_push($wifitalist, array_pop($line_row_arr['wifidata']['wifitalist']));
                        }
                    }

                    $all_content['wifidata']['count']  = count($wifitalist);
                    $all_content['wifidata']['wifitalist']  = $wifitalist;
                }



                file_put_contents('./data/test_trans.txt', json_encode($all_content));
                Util\Util::curl_post(json_encode($all_content), $url);
                unlink($dest_filename);


            }
        }
    }

}